package ord2.impl.searcher;

import java.util.List;
import ord2.core.Parameter;
import ord2.core.AbstractQuery;
import ord2.core.Result;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import ord2.search.AbstractParametricSearcher;
import org.apache.lucene.analysis.br.BrazilianAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.SimpleFSDirectory;
import org.apache.lucene.util.Version;
/**
 *
 * @author José Ivan
 * @author Edviges
 */
public class LuceneSearcher extends AbstractParametricSearcher<String, File> {

    private IndexSearcher searcher = null;
    
    public LuceneSearcher(Parameter[] pars) throws IOException {
    
        super(pars);
    }
    
    @Override
    public List<Result<File>> query(AbstractQuery<String> query) {
        
        return this.query(query, null);
    }

    @Override
    public List<Result<File>> query(AbstractQuery<String> query, Parameter[] pars) {

        try {
            
            //Inicia o searcher
            if (this.searcher == null) {

                initSeacher();
            }
        } catch(IOException io) {
            
            return null;
        }
        
        LinkedList<Result<File>> res = new LinkedList<Result<File>>();
        
        try {

            QueryParser qp = new QueryParser(Version.LUCENE_31, "content",
                new BrazilianAnalyzer(Version.LUCENE_31));
            Query q = qp.parse(query.getQuery());
            TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
            this.searcher.search(q, collector);
            for (ScoreDoc td : collector.topDocs().scoreDocs) {
                
                Document doc = this.searcher.doc(td.doc);
                res.add(new Result<File>("document",
                        new File(doc.getField("path").stringValue())));
            }
        } catch (Exception e) {
            
            return null;
        }

        try {
            
            searcher.close();
        } catch (IOException e) {

        }

        searcher = null;
        return res;
    }
    
    private void initSeacher() throws IOException {
        
        String path = null;
        for (Parameter p : this.getParameters()) {
        
            if (p.getName().equals("path")) {
                
                path = p.getValue();
                break;
            }
        }
        
        searcher = new IndexSearcher(new SimpleFSDirectory(new File(path)));
    }
}
